package com.lzy.business.controller.dept;

import com.lzy.base.apis.DeptServiceApi;
import com.github.pagehelper.PageInfo;
import com.lzy.base.dtos.DeptDto;
import com.lzy.business.facade.ProductDeptFacade;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.product.dtos.ProductDeptDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
 * <p>
 * Created by ellengou on 2017/5/2 0002.
 * since 2.0
 */
@Controller
@Scope("prototype")
@RequestMapping(value = "/admin/dept")
public class DeptController {

    protected Logger logger = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptServiceApi deptServiceApi;
    @Autowired
    private ProductDeptFacade deptFacade;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return "dept/dept_list";
    }

    @RequestMapping(value = "deptList", method = RequestMethod.GET)
    @ResponseBody
    public PageBean deptList(@RequestParam(value = "deptId") Long parentDeptId, Pager page) {
        PageBean pageBean = new PageBean();
        try {
            PageInfo info = deptServiceApi.getSubDeptDtosByPage(parentDeptId, true, page);
            pageBean = new PageBean<>(info.getTotal(), info.getList());
        } catch (Exception e) {
            logger.error("查询部门时发生错误！", e);
        }
        return pageBean;
    }

    /**
     * 查询部门列表数据   返回json在页面
     */
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    @ResponseBody
    public PageBean deptAllList(DeptDto request) {
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<DeptDto> pageInfo = deptServiceApi.getAllDeptList(pager, request);
        return new PageBean(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), DeptDto.class));
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, String>> deptTree() {
        List<DeptDto> deptList = deptServiceApi.getDeptDtos(null);
        List<Map<String, String>> deptTreeNods = new ArrayList<>();
        for (DeptDto d : deptList) {
            Map<String, String> node = new HashMap<>();
            node.put("id", String.valueOf(d.getId()));
            node.put("text", d.getDeptName());
            if (null != d.getParentId()) {
                node.put("parent", String.valueOf(d.getParentId()));
            } else {
                node.put("parent", "#");
            }
            deptTreeNods.add(node);
        }
        return deptTreeNods;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ProductDeptDto view(@PathVariable("id") Long id) {
        ProductDeptDto deptDto = deptFacade.findDeptDtoById(id);
        return deptDto;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Result create(ProductDeptDto dept, BindingResult result) throws Exception {
        //验证部门唯一部门编码
        DeptDto validationDto = new DeptDto();
        validationDto.setDeptCode(dept.getDeptCode());
        List<DeptDto> exitsDept = deptServiceApi.getAll(validationDto);
        Ensure.that(null != exitsDept && !exitsDept.isEmpty()).isFalse("01001101");
        //验证部门唯一名称
        validationDto = new DeptDto();
        validationDto.setDeptName(dept.getDeptName());
        exitsDept = deptServiceApi.getAll(validationDto);
        Ensure.that(null != exitsDept && !exitsDept.isEmpty()).isFalse("01001135");
        Boolean addOk = deptFacade.createDept(dept);
        Ensure.that(addOk).isTrue("01001102");
        return new Result();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(@Valid ProductDeptDto dept) {
        Boolean flag;
        DeptDto validationDto = new DeptDto();
        validationDto.setDeptCode(dept.getDeptCode());
        validationDto.setId(dept.getId());
        flag = deptServiceApi.checkUpdate(validationDto);
        Ensure.that(flag).isFalse("01001101");
        validationDto = new DeptDto();
        validationDto.setDeptName(dept.getDeptName());
        validationDto.setId(dept.getId());
        flag = deptServiceApi.checkUpdate(validationDto);
        Ensure.that(flag).isFalse("01001101");
        Boolean addOk = deptFacade.updateDept(dept);
        Ensure.that(addOk).isTrue("01001104");
        return new Result();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    public Result delete(@RequestParam("id") Long id) {
        List<DeptDto> subDeptList = deptServiceApi.getSubDeptDtos(id);
        Ensure.that(null != subDeptList && !subDeptList.isEmpty()).isFalse("01001105");
        Boolean deleteOk = deptServiceApi.deleteDeptDtoById(id);
        Ensure.that(deleteOk).isTrue("");
        return new Result();
    }

    /**
     * 做部门简称的唯一性校验
     *
     * @param dept
     * @return
     */
    @RequestMapping(value = "select/deptCode", method = RequestMethod.GET)
    @ResponseBody
    public Result selectDeptCode(DeptDto dept) {
        if (dept.getId() != null) {
            DeptDto validationDto = new DeptDto();
            validationDto.setDeptCode(dept.getDeptCode());
            validationDto.setId(dept.getId());
            Boolean flag = deptServiceApi.checkUpdate(validationDto);
            if (flag) {
                return new Result("1", "");
            }
        } else {
            //验证部门唯一部门编码
            DeptDto validationDto = new DeptDto();
            validationDto.setDeptCode(dept.getDeptCode());
            List<DeptDto> exitsDept = deptServiceApi.getAll(validationDto);
            if (exitsDept != null && exitsDept.size() > 0) {
                return new Result("1", "");
            }
        }
        return new Result();
    }

    /**
     * 做部门名称的唯一性校验
     *
     * @param dept
     * @return
     */
    @RequestMapping(value = "select/deptName", method = RequestMethod.GET)
    @ResponseBody
    public Result selectDeptName(DeptDto dept) {
        if (dept.getId() != null) {
            DeptDto validationDto = new DeptDto();
            validationDto.setDeptName(dept.getDeptName());
            validationDto.setId(dept.getId());
            Boolean flag = deptServiceApi.checkUpdate(validationDto);
            if (flag) {
                return new Result("1", "");
            }
        } else {
            //验证部门唯一名称
            DeptDto validationDto = new DeptDto();
            validationDto.setDeptName(dept.getDeptName());
            List<DeptDto> exitsDept = deptServiceApi.getAll(validationDto);
            if (exitsDept != null && exitsDept.size() > 0) {
                return new Result("1", "");
            }
        }
        return new Result();
    }
}
